import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
import React from 'react';
import PropTypes from 'prop-types';
import Button from 'antd/lib/button';
import Switch from 'antd/lib/switch';
import Notification from 'antd/lib/notification';
import Icon from 'antd/lib/icon';
import style from './style.scss';
import _ from 'lodash';


const SortableItem = SortableElement(({value,active,switchDo}) =>
  <li style={{
    position: 'relative',
    width: '100%',
    display: 'block',
    padding: 16,
    backgroundColor: '#FFF',
    borderBottom: '1px solid #EFEFEF',
    boxSizing: 'border-box',
    WebkitUserSelect: 'none',
  }}>{value}
    <div className={style.switch_container}>
      <Switch checked={active}  onChange={switchDo}/>
    </div>

  </li>
);

const SortableList = SortableContainer(({items,switchDo,that}) => {
  return (
    <ul style={{
      width: '100%',
      maxHeight:'calc(100vh - 128px)',
      margin: '0 auto',
      marginBottom: '10px',
      overflow: 'auto',
      backgroundColor: '#f3f3f3',
      border: '1px solid #EFEFEF',
      borderRadius: 3
    }}>

      {items.map(({name,active,id}, index) => (
          <SortableItem key={`item-${index}`} index={index} value={name} active={active} switchDo={switchDo.bind(that,{active,id})} />
      ))}

    </ul>
  );
});

export default class SortableComponent extends  React.Component {
  state = {
    items: [],
    loading: false
  }
  onSortEnd = ({oldIndex, newIndex}) => {
    let {items} = this.state;
    this.props.selectedModule(items[oldIndex])
    if(oldIndex === newIndex){
      console.log("顺序没有发生变化");
      return
    }

    this.setState({
      items: arrayMove(items, oldIndex, newIndex)
    },()=>{
      this.props.templateModifyTrue()
    })
  }
  componentWillReceiveProps(nextProps){
    let isDifferent = (nextProps.templateID !== this.state.templateID)
    if(isDifferent){
      this.setState({items: this.props.curModules, templateID: this.props.templateID})
    }
  }
  shouldComponentUpdate(nextProps, nextState){

    if(nextProps.templateID !== this.state.templateID ){
      // console.log("moduleID变化")
      return true
    }else{
      // console.log((this.state !== nextState)? "state变化" : "state不变化")
      return this.state !== nextState
    }
  }
  componentDidMount(){
    if(this.state.items.length === 0){
      this.setState({items: this.props.curModules, templateID: this.props.templateID })
    }
  }
  switch({active,id},switchTo){
    // console.log("switch",active,id,switchTo)
    let cloneModules = _.cloneDeep(this.state.items)
   let clickedModule =  _.find(cloneModules, {id,active})
    if(clickedModule){
      clickedModule.active = switchTo
      this.setState({items: cloneModules},()=>{
        this.props.templateModifyTrue()
      })
    }else{
      console.log("没有找到module")
    }
  }
  syncModules(){
    //同步模块顺序
    if(this.state.items.length === 0 || !this.props.templateModify){
      Notification.warning({
        message: '没有检测到更改！',
      });

      return
    }
    this.setState({loading: true})
    let request = this.props.sync({templateID: this.state.templateID, modules: this.state.items,templateName: this.props.templateName}, this.props.HospitalId)
    request.then((result)=>{
      if(result.payload.data.success){
        this.setState({loading: false});
        this.props.templateModifyFalse();
        Notification.success({
          message: '同步模块顺序&开关状态成功！'
        });
        this.props.reFetchData()
      }else{
        this.setState({loading: false});
        Notification.error({
          message: '同步失败！',
          description: '服务当前不可用'

        });
      }
    })
  }
  render() {
    return <div className={style.sort_list}>
      <SortableList items={this.state.items} onSortEnd={this.onSortEnd} that={this} switchDo={this.switch} helperClass="activedList" />
      <div className={style.align_center}>
        <Button type="primary" icon="sync" onClick={this.syncModules.bind(this)} loading={this.state.loading}>同步模块顺序 & 开关状态</Button>
      </div>
    </div>
  }
}

SortableComponent.propTypes = {
  curModules: PropTypes.array
};
